import api from './api';
import { Init } from './mixins';
import type { ElForm } from 'element-plus';
import { ref, reactive, toRaw } from 'vue';
import electronUtils from '~common/electron';
import { FilowDirItem as IFilowDirItem, default as Sqlite } from '~sqlite';

const sqlite: typeof Sqlite = require('~sqlite').default;

/**
 * 保存目录项对话框
 */
export function useDirItemDialog(that: Init) {
    let mode: 'add' | 'edit' = 'add';
    const formRefKey = 'dirItemDialogForm';

    const saveDialogVisible = ref(false);

    const formData = reactive({
        id: 0,
        name: '',
        path: '',
    });
    const formRule = {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        path: [{ required: true, message: '请输入路径', trigger: 'blur' }],
    };

    const initFormData = () => {
        formData.id = 0;
        formData.name = '';
        formData.path = '';
    };

    const saveDialogToggle = (flag: boolean, editData?: IFilowDirItem) => {
        if (editData) {
            mode = 'edit';
            editData = toRaw(editData);
            formData.id = editData.id;
            formData.name = editData.name;
            formData.path = editData.path;
        } else {
            mode = 'add';
        }

        saveDialogVisible.value = flag;
    };

    const openSelectDirDialog = async () => {
        const result = await electronUtils.showOpenDialog({ type: 'selectDir' });
        if (!result.isCancel) {
            formData.path = result.paths[0];
        }
    };

    const saveFormData = async () => {
        try {
            const validate = await (that.current.refs[formRefKey] as typeof ElForm).validate();
            if (validate) {
                const resolveInfo = await sqlite.filowDirItem.update(formData.id, formData.name, formData.path);

                if (resolveInfo.data) {
                    await that.getDirItemList();

                    if (mode === 'edit') {
                        that.dirItem.value = '';
                        that.dirCasc.value = '';
                        that.dirCascList.value = [];

                        that.initFileList();
                        that.initSelectFiles();
                    }

                    saveDialogVisible.value = false;
                    initFormData();
                }
            }
        } catch (e) {
            console.error(e);
        }
    };

    const close = () => {
        initFormData();
    };

    return {
        formData,
        formRule,
        formRefKey,
        saveDialogVisible,

        close,
        saveFormData,
        saveDialogToggle,
        openSelectDirDialog,
    };
}

/**
 * 创建目录对话框
 */
export function useCreateDirDialog(that: Init) {
    const formRefKey = 'createDirDialogForm';

    const formData = reactive({
        currentPath: '',
        dirName: '',
    });
    const formRule = {
        currentPath: [{ required: true, message: '请输入路径', trigger: 'blur' }],
        dirName: [{ required: true, message: '请输入目录名', trigger: 'blur' }],
    };

    const visible = ref(false);

    const initFormData = () => {
        formData.currentPath = '';
        formData.dirName = '';
    };

    const save = async () => {
        try {
            const validate = await (that.current.refs[formRefKey] as typeof ElForm).validate();
            if (validate) {
                const dirpath = formData.currentPath + '/' + formData.dirName;
                const result = await api.createFolder({ dirpath });

                if (result.success) {
                    visible.value = false;
                    initFormData();

                    const res = await api.getDirInnerAllFiles({ dirpath: that.dirItem.value });
                    if (res.success) {
                        that.dirCascList.value = res.data?.innerDirs || [];
                    }
                }
            }
        } catch (e) {
            console.error(e);
        }
    };

    const close = () => {
        initFormData();
    };

    return {
        visible,
        formData,
        formRule,
        formRefKey,

        save,
        close,
    };
}

/**
 * 转移目录对话框
 */
export function useTransferDirDialog(that: Init) {
    const visible = ref(false);
    const formRefKey = 'transferDirDialogForm';

    const formData = reactive({
        from: '',
        to: '',
    });
    const formRule = {
        from: [{ required: true, message: '请输入源地址', trigger: 'blur' }],
        to: [{ required: true, message: '请输入目标地址', trigger: 'blur' }],
    };

    const initFormData = () => {
        formData.from = '';
        formData.to = '';
    };

    const openSelectDirDialog = async () => {
        const result = await electronUtils.showOpenDialog({ type: 'selectDir' });
        if (!result.isCancel) {
            formData.to = result.paths[0];
        }
    };

    const save = async () => {
        try {
            const validate = await (that.current.refs[formRefKey] as typeof ElForm).validate();
            if (validate) {
                that.tips.value = '正在转移目录...';
                const dirname = that.getCurrentDirPath()?.split(/\/|\\/).pop();
                const result = await api.transferFolder({
                    from: formData.from + `/${dirname}`,
                    to: formData.to + `/${dirname}`,
                });
                if (result.success) {
                    visible.value = false;
                    initFormData();

                    const res = await api.getDirInnerAllFiles({ dirpath: that.dirItem.value });

                    that.dirCasc.value = '';
                    that.dirCascList.value = res.data?.innerDirs || [];

                    that.initSelectFiles();
                    await that.getDirInnerFiles(that.dirItem.value);
                }
            }
        } catch (e) {
            console.error(e);
        } finally {
            that.tips.value = '';
        }
    };

    const close = () => {
        initFormData();
    };

    return {
        visible,
        formData,
        formRule,
        formRefKey,

        save,
        close,
        openSelectDirDialog,
    };
}

/**
 * 重命名目录对话框
 */
export function useRenameDirDialog(that: Init) {
    const visible = ref(false);
    const formRefKey = 'renameDirDialogForm';

    const formData = reactive({
        currentPath: '',
        oldName: '',
        newName: '',
    });
    const formRule = {
        currentPath: [{ required: true, message: '请输入地址', trigger: 'blur' }],
        oldName: [{ required: true, message: '请输入旧目录名', trigger: 'blur' }],
        newName: [{ required: true, message: '请输入新目录名', trigger: 'blur' }],
    };

    const initFormData = () => {
        formData.currentPath = '';
        formData.oldName = '';
        formData.newName = '';
    };

    const save = async () => {
        try {
            const validate = await (that.current.refs[formRefKey] as typeof ElForm).validate();
            if (validate) {
                const oldpath = formData.currentPath + '/' + formData.oldName;
                const newpath = formData.currentPath + '/' + formData.newName;
                const result = await api.renameFileOrFolder({ oldpath, newpath });

                if (result.success) {
                    visible.value = false;
                    initFormData();

                    const res = await api.getDirInnerAllFiles({ dirpath: that.dirItem.value });
                    if (res.success) {
                        that.dirCascList.value = res.data?.innerDirs || [];
                        that.dirCasc.value = newpath;
                        that.initSelectFiles();
                        await that.getDirInnerFiles(newpath);
                    }
                }
            }
        } catch (e) {
            console.error(e);
        }
    };

    const close = () => {
        initFormData();
    };

    return {
        visible,
        formData,
        formRule,
        formRefKey,

        save,
        close,
    };
}

/**
 * 转移文件对话框
 */
export function useTransferFileDialog(that: Init) {
    const visible = ref(false);
    const formRefKey = 'transferFileDialogForm';

    const formData = reactive({
        from: '',
        to: '',
    });
    const formRule = {
        from: [{ required: true, message: '请输入源地址', trigger: 'blur' }],
        to: [{ required: true, message: '请输入目标地址', trigger: 'blur' }],
    };

    const initFormData = () => {
        formData.from = '';
        formData.to = '';
    };

    const openSelectDirDialog = async () => {
        const result = await electronUtils.showOpenDialog({ type: 'selectDir' });
        if (!result.isCancel) {
            formData.to = result.paths[0];
        }
    };

    const save = async () => {
        try {
            const validate = await (that.current.refs[formRefKey] as typeof ElForm).validate();
            if (validate) {
                that.tips.value = '正在转移文件...';
                const allSelectFiles = that.getAllSelectFiles();
                const params = {
                    list: allSelectFiles.map(m => {
                        const filename = m.split('/').pop();
                        return {
                            from: formData.from + '/' + filename,
                            to: formData.to,
                        };
                    }),
                };
                const result = await api.transferFile(params);

                if (result.success) {
                    visible.value = false;
                    initFormData();

                    that.initSelectFiles();

                    await that.getDirInnerFiles();
                }
            }
        } catch (e) {
            console.error(e);
        } finally {
            that.tips.value = '';
        }
    };

    const close = () => {
        initFormData();
    };

    return {
        visible,
        formData,
        formRule,
        formRefKey,

        save,
        close,
        openSelectDirDialog,
    };
}
